import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { withTranslation } from 'react-i18next';
import { Slider, Typography } from 'antd';
import classnames from 'classnames';

import './SlabThicknessSlider.styl';

const SLIDER = {
  MIN: 0.1,
  MAX: 500,
  STEP: 0.1,
};

const _applySlabThickness = (
  value,
  toolbarClickCallback,
  button,
  isVisible
) => {
  if (!(isVisible && toolbarClickCallback)) {
    return;
  }

  const generateOperation = (operation, value) => {
    // Combine slider value into slider operation
    const generatedOperation = { ...operation };
    generatedOperation.commandOptions = {
      ...operation.commandOptions,
      slabThickness: value,
    };

    return generatedOperation;
  };

  const operation = generateOperation(button, value);
  toolbarClickCallback(operation, event);
};

function SlabThicknessSlider({
  toolbarClickCallback,
  button,
  activeButtons,
  isActive,
  className,
  isVisible,
  t
}) {
  const [state, setState] = useState({
    value: SLIDER.MIN,
    sliderMin: SLIDER.MIN,
    sliderMax: SLIDER.MAX,
  });

  const onChangeSlider = value => {
    setState({ ...state, value });
  }

  useEffect(() => {
    _applySlabThickness(state.value, toolbarClickCallback, button, isVisible);
  }, [state.value, toolbarClickCallback, button, isVisible]);

  const { id, label } = button;

  return (
    <div style={{ width: '100px' }} className={classnames('toolbar-button', 'slab-thickness', className)}>
      <div className="thickness-wrap">
        <Slider
          value={state.value}
          min={state.sliderMin}
          max={state.sliderMax}
          step={SLIDER.STEP}
          onChange={onChangeSlider}
          id={id}
          tooltipPlacement="bottom"
          tipFormatter={value => `${value}mm`}
        />
        <Typography.Text>{t(label)}</Typography.Text>
      </div>
    </div>
  );
}

SlabThicknessSlider.propTypes = {
  toolbarClickCallback: PropTypes.func.isRequired,
  button: PropTypes.object.isRequired,
  activeButtons: PropTypes.array.isRequired,
  isActive: PropTypes.bool,
  className: PropTypes.string,
  isVisible: PropTypes.bool,
  t: PropTypes.func.isRequired,
};

export default withTranslation("Buttons")(SlabThicknessSlider);
